package org.utils.rmi;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.Socket;
import java.rmi.server.RMIClientSocketFactory;

public class SSLClientSocketFactory implements RMIClientSocketFactory
{
	private static final String DEFAULT_CLASS_NAME = "javax.net.ssl.SSLSocket";
	
	private Constructor cons = null;
	
	public static SSLClientSocketFactory getDefaultFactory()
		throws SSLSocketFactoryException
	{
		return SSLClientSocketFactory.getFactory(DEFAULT_CLASS_NAME);
	}
	
	public static SSLClientSocketFactory getFactory(String className)
		throws SSLSocketFactoryException
	{
		return new SSLClientSocketFactory(className);
	}

	public static SSLClientSocketFactory getFactory(Class pClass)
		throws SSLSocketFactoryException
	{
		return new SSLClientSocketFactory(pClass);
	}
	protected SSLClientSocketFactory(String sslSocketClassName)
		throws SSLSocketFactoryException
	{
	   try
	   {
		Class sslSocketClass = Class.forName(sslSocketClassName);
		Class[] cTypes = { String.class, Integer.TYPE };
		cons = sslSocketClass.getConstructor(cTypes);
	   }
	   catch (Exception e)
	   {
	   	throw new SSLSocketFactoryException(e);
	   }
	}

	protected SSLClientSocketFactory(Class sslSocketClass)
		throws SSLSocketFactoryException
	{
	   try
	   {
		Class[] cTypes = { String.class, Integer.TYPE };
		cons = sslSocketClass.getConstructor(cTypes);
	   }
	   catch (Exception e)
	   {
	   	throw new SSLSocketFactoryException(e);
	   }
	}

	public Socket createSocket(String host, int port) 
		throws IOException
 	{
 		try
 		{
			Object[] args = { host, new Integer(port) };
			return (Socket) cons.newInstance(args);
		}
		catch (Exception e)
		{
			throw new IOException(e.toString());
		}
 	}
}
